﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;

using umbraco.interfaces;

namespace CreativeMinds.Umbraco.DataTypes.CultureInfoSelector {

	public class CultureInfoSelectorEditor : DropDownList, IDataEditor {
		private IData data;
		private SortedList prevalues;

		public CultureInfoSelectorEditor(IData data, SortedList prevalues) {
			this.data = data;
			this.prevalues = prevalues;
		}

		public Control Editor {
			get {
				return this;
			}
		}

		public virtual bool TreatAsRichTextEditor {
			get {
				return false;
			}
		}
		public virtual bool ShowLabel {
			get {
				return true;
			}
		}

		public void Save() {
			string value = "";
			if (this.SelectedIndex > 0) {
				value = this.SelectedValue;
			}
			data.Value = value;
		}

		private static object sortedLock = new object();
		private static SortedDictionary<string, CultureInfo> sorted = null;
		protected override void OnInit(EventArgs e) {
			base.OnInit(e);

			if (sorted == null) {
				lock (sortedLock) {
					if (sorted == null) {
						SortedDictionary<string, CultureInfo> temp = new SortedDictionary<string, CultureInfo>();
						CultureInfo[] infos = CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures);
						foreach (CultureInfo info in infos) {
							if (!info.IsNeutralCulture) {
								temp.Add(info.Name, info);
							}
						}
						sorted = temp;
					}
				}
			}

			foreach (KeyValuePair<string, CultureInfo> pair in sorted) {
				ListItem item = new ListItem();
				item.Text = pair.Value.DisplayName;
				item.Value = pair.Value.Name;
				this.Items.Add(item);
			}

			if (data != null && data.Value != null) {
				this.SelectedValue = data.Value.ToString();
			}
		}
	}
}